//
//  RegisterViewController.m
//  haolaDoc
//
//  Created by chen on 2017/5/16.
//  Copyright © 2017年 deyi. All rights reserved.
//

#import "RegisterViewController.h"
#import "AppMonitor.h"
#define COUNTDOWN_TIME 60
@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _registerScrollView.contentSize=CGSizeMake(0, self.view.frame.size.height);
    self.isAgree=false;
    [_cellPhoneField addTarget:self  action:@selector(cellPhoneFieldListener)  forControlEvents:UIControlEventAllEditingEvents];
    [_rePasswordField addTarget:self  action:@selector(inputStatusListener)  forControlEvents:UIControlEventAllEditingEvents];
    // Do any additional setup after loading the view.
    self.cellPhoneView.layer.cornerRadius=5;
    self.verifyPasswordView.layer.cornerRadius=5;
    self.regieterBtn.userInteractionEnabled=NO;
    self.regieterBtn.alpha=0.4;
    self.getVerifyCodeBtn.userInteractionEnabled=NO;
    self.getVerifyCodeBtn.alpha=0.4;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)inputStatusListener{
    _cellPhoneNumber=self.cellPhoneField.text;
    _verifyCode=self.verifyCodeField.text;
    _username=self.usernameField.text;
    _password=self.passwordField.text;
    _rePassword=self.rePasswordField.text;
    if(_cellPhoneNumber.length>0&&_verifyCode.length>0&&_username.length>0&&_password.length>0&&_rePassword.length>0&&self.isAgree){
        if (_password==_rePassword) {
            self.regieterBtn.userInteractionEnabled=YES;
            self.regieterBtn.alpha=1.0;
        }
    }else{
        self.getVerifyCodeBtn.userInteractionEnabled=NO;
        self.getVerifyCodeBtn.alpha=0.4;
    }
}
-(void)cellPhoneFieldListener{
    _cellPhoneNumber=self.cellPhoneField.text;
    if(self.cellPhoneNumber.length>0&&[AppMonitor isMobileNumber:_cellPhoneNumber]){
        self.getVerifyCodeBtn.userInteractionEnabled=YES;
        self.getVerifyCodeBtn.alpha=1.0;
    }else{
        self.getVerifyCodeBtn.userInteractionEnabled=NO;
        self.getVerifyCodeBtn.alpha=0.4;
    }
}

- (IBAction)onVerifyBtnClick:(id)sender {
    if ([AppMonitor isConnectionAvailable]) {
       [self doGetVerifyCodeActionWithCellphoneNumber:_cellPhoneNumber];
    }else{
       [AppMonitor showResultWithOwner:self withStatus:@"无网络连接" actionOk:nil];
    }
    
}
/**
 *  网络畅通情况下通过手机号码进行验证码请求
 *
 *  @param cellphoneNumber 手机号码
 */
-(void)doGetVerifyCodeActionWithCellphoneNumber:(NSString *)cellphoneNumber{
    NSString *urlStr=[NSString stringWithFormat:BASE_URL@"/doctorinfo/checkTel/%@",cellphoneNumber];
    NSURL *url=[NSURL URLWithString:urlStr];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    NSError *error;
    NSData *receiveData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:receiveData options:NSJSONReadingMutableContainers error:nil];//转换数据格式
    NSString *status= [content objectForKey:@"status"];
    NSString *msg= [content objectForKey:@"msg"];
    if([status isEqualToString:@"failed"]){
        [SVProgressHUD showWithStatus:msg];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:0.7];
    }else{
        [self waitForSixtySecond];
    }
}
/**
 *  设置请求验证码的按钮状态和颜色
 */
-(void)waitForSixtySecond{
    self.getVerifyCodeBtn.userInteractionEnabled=NO;
    self.getVerifyCodeBtn.alpha=0.4;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    _timeDisplay = COUNTDOWN_TIME;
    
}
/**
 *  按钮的状态控制定时器
 *
 *  @param sender 消息发送者
 */
-(void)timerFireMethod:(id)sender{
    
    _timeDisplay=_timeDisplay-1;
    NSString *displayStr = [NSString stringWithFormat:@"%i s",_timeDisplay];
    [self.getVerifyCodeBtn setTitle:displayStr forState:UIControlStateNormal];
    if (_timeDisplay==0) {
        [_timer invalidate];
        _timer=nil;
        self.getVerifyCodeBtn.userInteractionEnabled=YES;
        self.getVerifyCodeBtn.alpha=1.0;
        [self.getVerifyCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }else{
        self.getVerifyCodeBtn.userInteractionEnabled=NO;
        self.getVerifyCodeBtn.alpha=0.4;
    }
}
/**
 *  注册按钮点击事件
 *
 *  @param sender 事件发起者
 */
- (IBAction)onRegisterBtnClick:(id)sender {
    if ([AppMonitor isConnectionAvailable]) {
        [self doRegisterActionWithCellphonenumber:_cellPhoneNumber andVerifyCode:_verifyCode andUsername:_username andPassword:_password];
        [[self navigationController] popViewControllerAnimated:YES];
    }else{
        [SVProgressHUD showWithStatus:@"无网络连接"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:0.7];
    }
}
/**
 *  在网络正常的情况下进行注册请求
 *
 *  @param cellphoneNumber 手机号码
 *  @param verifyCode      验证码
 *  @param username        用户名
 *  @param password        密码
 */
-(void)doRegisterActionWithCellphonenumber:(NSString *)cellphoneNumber andVerifyCode:(NSString *)verifyCode andUsername:(NSString *)username andPassword:(NSString *)password{
    username = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlStr=[NSString stringWithFormat:BASE_URL@"/doctorinfo/saveRegisterInfo/%@-%@-%@-%@",cellphoneNumber,verifyCode,username,password];
    NSURL *url=[NSURL URLWithString:urlStr];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    NSError *error;
    NSData *receiveData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:receiveData options:NSJSONReadingMutableContainers error:nil];//转换数据格式
    NSString *status = [content objectForKey:@"status"];
    NSString *message = [content objectForKey:@"msg"];
    if ([status isEqualToString:@"success"]) {
        [SVProgressHUD showWithStatus:@"注册成功"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:0.7];
    }else{
        [SVProgressHUD showWithStatus:message];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:0.7];
    }
}
-(void)dismiss{
    [SVProgressHUD dismiss];
}
/**
 *  同意注册协议的按钮
 *
 *  @param sender 消息发起者
 */
- (IBAction)onAgreeProtocol:(id)sender {
    self.isAgree=!self.isAgree;
    if (self.isAgree) {
        [self.protocolCheckBox setImage:[UIImage imageNamed:@"check_selected.png"] forState:UIControlStateNormal];
        
    }else{
        [self.protocolCheckBox setImage:[UIImage imageNamed:@"check_unselected.png"] forState:UIControlStateNormal];
    }
    [self inputStatusListener];
}

@end
